﻿$().ready(function () {
    $("#breadcrumb").append('<li><a href="' + $("#urlSupplier").val() + '" title="Lista de proveedores">Lista de proveedores</a></li>');
    $("#optSupplier").addClass("HoverOnList");

    $.datepicker.regional['es'] = {
        closeText: 'Cerrar',
        prevText: '<Ant',
        nextText: 'Sig>',
        currentText: 'Hoy',
        monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
        monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
        dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Juv', 'Vie', 'Sáb'],
        dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };
    $.datepicker.setDefaults($.datepicker.regional['es']);

    var validator = $("#frmSupplier").bind("invalid-form.validate", function () {
        //$("#lblErrorMsgPerson").show();
    }).validate({
        debug: true,
        rules: {
            identification: {
                required: true,
                minlength: 2
            },
            name: {
                required: true,
                minlength: 1
            },
            firstName: {
                required: true,
                minlength: 1
            },
            lastName: {
                required: true,
                minlength: 1
            },
            email: {
                required: false,
                email: true
            },
            phone: {
                required: false,
                digits: true
            },
            strBirthDate: {
                required: false,
                date: true
            },
            webSite: {
                required: false,
                url: true
            },
            fax: {
                required: false,
                digits: true
            },
        },
        messages: {
            identification: "La identificación es requerida",
            name: "El nombre es requerido",
            firstName: "El primer apellido es requerido",
            lastName: "El segundo apellido es requerido",
            email: "El correo electrónico es inválido",
            phone: "El teléfono es inválido. Solo ingrese números.",
            strBirthDate: "La fecha es inválida.",
            webSite: "La página Web es inválida. Formato correcto: http://www.website.com",
            fax: "El fax es inválido. Solo ingrese números."
        }
    });

    $("#txtBirthDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("input[type='radio']").change(function () {
        if ($('#rdbOrganization').is(':checked')) {
            $('#divOrganization').show();
            $('#divPerson').hide();
            $('#pnlFaxWebsite').show();

            $("#txtLegalEntityName").removeAttr("disabled");
            $("#txtCorporateName").removeAttr("disabled");
            $("#txtContactName").removeAttr("disabled");
            $("#txtComments").removeAttr("disabled");

            $("#txtFirstName").attr("disabled", "disabled");
            $("#txtLastName").attr("disabled", "disabled");
            $("#cmbMaritalStatus").attr("disabled", "disabled");
            $("#txtBirthDate").attr("disabled", "disabled");
            $("#txtBirthPlace").attr("disabled", "disabled");
        }
        else {
            $('#divOrganization').hide();
            $('#divPerson').show();
            $('#pnlFaxWebsite').hide();

            $("#txtLegalEntityName").attr("disabled", "disabled");
            $("#txtCorporateName").attr("disabled", "disabled");
            $("#txtContactName").attr("disabled", "disabled");
            $("#txtComments").attr("disabled", "disabled");

            $("#txtFirstName").removeAttr("disabled");
            $("#txtLastName").removeAttr("disabled");
            $("#cmbMaritalStatus").removeAttr("disabled");
            $("#txtBirthDate").removeAttr("disabled");
            $("#txtBirthPlace").removeAttr("disabled");
        }
    });

    ///Toolbar
    $('#btnClear').live('click', function () {
        ClearForm();
    });

    $('#btnNew').live('click', function () {
        if (confirm('¿Desea abandonar la edición y crear un registro nuevo?')) {
            window.location = $('#urlCreate').val();
        }
    });

    ///Menu
    $('#menuClear').live('click', function () {
        ClearForm();
    });

    $('#menuNew').live('click', function () {
        if (confirm('¿Desea abandonar la edición y crear un registro nuevo?')) {
            window.location = $('#urlCreate').val();
        }
    });

    $('#btnSearch').click(function () {
        Search();
    });

    $("#txtStartDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtEndDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    var thumb = $('#imgPhoto');
    var thumb2 = $('#imgPhotoPreview');
    if (!(typeof thumb[0] === "undefined")) {
        new AjaxUpload('imgPhoto', {
            action: $("#urlUploadPhoto").val(),
            name: 'image',
            onSubmit: function (file, extension) { },
            onComplete: function (file, response) {
                $("#urlphoto").val(response);
                var url = '/ODSYSUI/Content/Images/Uploads/Supplier/' + response;
                thumb.attr('src', url);
                thumb2.attr('src', url);
            }
        });
    }

    if (!(typeof $('#txtPersonFilter')[0] === "undefined")) {
        InitAutocomplete();
    }
});

function ConfirmDelete(id) {
    if (confirm('¿Esta seguro que desea eliminar el registro?')) {
        DeleteSupplier(id);
    }
}

function DeleteSupplier(objectId) {
    $.ajax(
    {
        type: "POST",
        url: $('#urlDelete').val(),
        data:
            JSON.stringify({
                id: objectId
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = "/ODSYSUI/Supplier/SetMessage?id=1";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = "/ODSYSUI/Supplier/SetMessage?id=2";
        }
    });
}

function ClearForm() {
    $("#imgPhoto").attr("src", $('#urlPhoto').val());

    var cmbSupplierType = $('#cmbSupplierType');
    if (cmbSupplierType.length > 0) {
        cmbSupplierType[0].selectedIndex = 0;
    }

    var cmbMaritalStatus = $('#cmbMaritalStatus');
    if (cmbMaritalStatus.length > 0) {
        cmbMaritalStatus[0].cmbMaritalStatus = 0;
    }

    var cmbCountry = $('#cmbCountry');
    if (cmbCountry.length > 0) {
        cmbCountry[0].cmbCountry = 0;
    }

    $('#txtID').val('');
    $('#txtName').val('');
    $('#txtLegalEntityName').val('');
    $('#txtCorporateName').val('');
    $('#txtContactName').val('');
    $('#txtComments').val('');

    $('#txtFirstName').val('');
    $('#txtLastName').val('');
    $('#txtBirthDate').val('');
    $('#txtBirthPlace').val('');

    $('#txtEmail').val('');
    $('#txtState').val('');
    $('#txtCity').val('');
    $('#txtZip').val('');
    $('#txtZip').val('');
    $('#txtAddress').val('');

    $('.field-validation-error').remove();
    $(":input").removeClass("input-validation-error");
}

function InitAutocomplete() {
    $("#txtPersonFilter").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: $('#urlGetSuppliers').val(),
                dataType: "json",
                data: {
                    searchString: request.term,
                    IsByName: $('#rdbNameFilter').is(':checked'),
                    maxRows: 12
                },
                parse: function (data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].name, result: data[i].name };
                    }
                    return rows;
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.name + ". ID: " + item.identification,
                            ID: item.partyID,
                            Name: item.name,
                            Identification: item.identification
                        }
                    }));
                },
                error: function (data, status, e) {
                    debugger;
                    alert(e);
                }
            });
        },
        minLength: 0,
        select: function (event, ui) {
            $('#partyID').val(ui.item.ID);
        }
    });

    $("#txtPersonFilter").keyup(function () {
        if (!this.value) {
            $('#partyID').val();
        }
    });
}

function Search() {
    var startDate = $('#txtStartDate').val();
    var endDate = $('#txtEndDate').val();
    var date1 = null;
    var date2 = null;

    if (startDate != "") {
        var d1 = parseInt(startDate.substring(0, 2));
        var m1 = parseInt(startDate.substring(3, 5)) - 1;
        var y1 = parseInt(startDate.substring(6, 10));
        date1 = new Date(y1, m1, d1);
    }

    if (endDate != "") {
        var d1 = parseInt(endDate.substring(0, 2));
        var m1 = parseInt(endDate.substring(3, 5)) - 1;
        var y1 = parseInt(endDate.substring(6, 10));
        date2 = new Date(y1, m1, d1);
    }

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlSearch").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                partyTypeID: $('#cmbPartyType').val(),
                startDate: date1,
                endDate: date2,
                isByName: $('#rdbNameFilter').is(':checked'),
                personFilter: $('#txtPersonFilter').val(),
                partyID: $('#partyID').val(),
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlSearch").val();
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            debugger;
            //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}

function SubmitForm() {
    if ($("#frmSupplier").valid()) {
        document.forms['frmSupplier'].submit();
    }
}